<template>
  <n-data-table :data="data" :loading="loading" :pagination="pagination" remote />
</template>

<script lang="ts">
import { defineComponent, PropType, ref, toRaw } from 'vue'
import { PaginationProps } from 'naive-ui'
import { LoadDataFunction } from '.'

export default defineComponent({
  name: 'STable',
  props: {
    loadData: {
      type: Function as PropType<LoadDataFunction>,
      require: true
    }
  },
  setup(props) {
    const data = ref()
    const loading = ref(false)
    const pagination = ref<PaginationProps>({
      itemCount: 0,
      pageCount: 1,
      page: 1,
      pageSlot: 6,
      pageSize: 10,
      onChange: page => {
        loadDataExtend(page)
      }
    })
    const loadDataExtend = (page: number = pagination.value.page ?? 1) => {
      loading.value = true
      const paginationToRaw = toRaw(pagination.value)
      props
        .loadData?.({ page: page, limit: paginationToRaw.pageSize })
        .then(res => {
          pagination.value = {
            ...paginationToRaw,
            itemCount: res.total,
            pageCount: Math.ceil(res.total / (pagination.value.pageSize || 1)),
            page: res.page
          }
          data.value = res.data
        })
        .finally(() => {
          loading.value = false
        })
    }
    loadDataExtend()

    return {
      refresh: (bool = false) => {
        bool ? loadDataExtend(1) : loadDataExtend()
      },
      loadDataExtend,
      loading,
      data,
      pagination
    }
  }
})
</script>

<style lang="less" scoped></style>
